package com.feng.zshop.backend.service.impl;

import com.feng.zshop.backend.dao.SysuserDao;
import com.feng.zshop.backend.param.SysuserParam;
import com.feng.zshop.backend.service.SysuserService;
import com.feng.zshop.backend.vo.SysuserVO;
import com.feng.zshop.common.constant.SysuserConstant;
import com.feng.zshop.common.exception.ServiceException;
import com.feng.zshop.model.Role;
import com.feng.zshop.model.Sysuser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author Lee
 * @date 2019/2/23
 */
@Service
public class SysuserServiceImpl implements SysuserService {

    @Autowired
    private SysuserDao sysuserDao;

    @Override
    public List<Sysuser> findAllSysuser() {
        return sysuserDao.listAllSysuser();
    }

    @Transactional
    @Override
    public void deleteSysuserById(Integer id) {
        sysuserDao.deleteSysuserById(id);
    }

    @Override
    public Sysuser getSysuserById(Integer id) {
        return sysuserDao.getSysuserById(id);
    }

    @Transactional
    @Override
    public void add(SysuserVO sysuserVO) throws ServiceException {
        Sysuser sysuser = new Sysuser();
        BeanUtils.copyProperties(sysuserVO, sysuser);
        sysuser.setCreateDate(new Date());
        sysuser.setValid(SysuserConstant.USER_ENABLE);
        Role role = new Role();
        role.setId(sysuserVO.getRoleId());
        sysuser.setRole(role);
        try {
            sysuserDao.insert(sysuser);
        } catch (Exception e) {
            throw new ServiceException("用户保存失败");
        }
    }

    @Transactional
    @Override
    public void modify(SysuserVO sysuserVO) throws ServiceException {
        Sysuser sysuser = new Sysuser();
        BeanUtils.copyProperties(sysuserVO, sysuser);
        Role role = new Role();
        role.setId(sysuserVO.getRoleId());
        sysuser.setRole(role);
        try {
            sysuserDao.update(sysuser);
        } catch (Exception e) {
            throw new ServiceException("用户保存失败");
        }
    }

    @Transactional
    @Override
    public void modifyStatusById(Integer id) {
        Sysuser sysuser = sysuserDao.getSysuserById(id);
        if (sysuser.getValid() == 1){
            sysuserDao.updateStatusById(id,SysuserConstant.USER_DISABLE);
        } else {
            sysuserDao.updateStatusById(id, SysuserConstant.USER_ENABLE);
        }
    }

    @Override
    public List<Sysuser> selectByCondition(SysuserParam sysuserParam) {
        return sysuserDao.listByCondition(sysuserParam);
    }

    @Override
    public Sysuser findByLoginNameAndPassword(String loginName, String password) {
        return sysuserDao.getByLoginNameAndPassword(loginName, password);
    }
}
